#!/bin/sh

function checkIsOk() {
   # $1 操作名

   if [[ $? > 0 ]]; then
      echo "${1} is failed"
      exit 1
   fi
   echo "${1} is success"
}

function restart() {
   # $1 服务名

   export GOPATH='/root/aist/goProject'
   export GO111MODULE='on'
   export GOPROXY='https://goproxy.cn'
   # kill 老的服务
   psServerCmd=$(ps -ef | grep "${1}" | grep -v grep)
   oldPid=$(echo ${psServerCmd} | awk '{print $2}')
   echo "kill ps: ${psServerCmd}"
   echo "old server pid: ${oldPid}"
   if [[ $oldPid > 0 ]]; then
      kill -9 $oldPid
   fi
   sleep 1

   # 启动服务
   nohup ./$1 >>./out.log 2>&1 &
   sleep 1

   # 获取启动的服务的 pid, 判断是否成功, 前后两个命令需要一致
   psServerCmd=$(ps -ef | grep "${1}" | grep -v grep)
   serverPid=$(echo ${psServerCmd} | awk '{print $2}')
   echo "strat ps: ${psServerCmd}"
   echo "new server pid: ${serverPid}"
   if [[ $serverPid == "" ]]; then
      echo "服务: ${1} 启动失败!!!"
      exit 1
   fi
   echo "启动服务: ${1} 成功"
}

function main() {
   # $1 服务名

   # 服务名
   serverName=$1
   git pull && checkIsOk "git pull"

   # 构建
   go build -o=$serverName main.go && checkIsOk "go build"

   # 启动
   restart $serverName
}

# 入口
main "tool"
